﻿//-------------
// <copyright file="RoleController.cs" company="Uncas">
//     Copyright (c) Ole Lynge Sørensen. All rights reserved.
// </copyright>
//-------------

namespace Uncas.Katas.SimpleMembership.Web.Controllers
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using Uncas.Katas.SimpleMembership.Domain;
    using Uncas.Katas.SimpleMembership.Web.Mappers;
    using Uncas.Katas.SimpleMembership.Web.ViewModels;

    /// <summary>
    /// Controller for role pages.
    /// </summary>
    public class RoleController : Controller
    {
        /// <summary>
        /// The user repository.
        /// </summary>
        private readonly IUserRepository repository;

        /// <summary>
        /// Initializes a new instance of the <see cref="RoleController"/> class.
        /// </summary>
        /// <param name="repository">The repository.</param>
        public RoleController(IUserRepository repository)
        {
            this.repository = repository;
        }

        /// <summary>
        /// Indexes this instance.
        /// </summary>
        /// <returns>The view with the list of roles.</returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index()
        {
            IEnumerable<Role> roles = this.repository.GetAllRoles();
            var result = roles.Select(
                r => RoleMapper.MapRoleToListItemViewModel(r));
            return View(result);
        }

        /// <summary>
        /// Indexes the specified role name.
        /// </summary>
        /// <param name="roleName">Name of the role.</param>
        /// <returns>Redirect to index.</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(string roleName)
        {
            this.repository.CreateRole(roleName);
            return RedirectToAction("Index");
        }

        /// <summary>
        /// Detailses the specified role name.
        /// </summary>
        /// <param name="roleName">Name of the role.</param>
        /// <returns>The view with the details of the role.</returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Details(string roleName)
        {
            IEnumerable<string> userNames =
                this.repository.GetUsersInRole(roleName);
            var result = new RoleDetailsViewModel
            {
                RoleName = roleName,
                UserNames = userNames
            };
            return View(result);
        }
    }
}
